/*
 * by lzh
 * 蜂巢1.5.5新增
 * */

'use strict';
angular.module('app')
    /* 添加自定义弹窗 */
    .directive('addModules', function () {
      return {
        restrict: 'E',
        templateUrl: "./src/app/toolChest/loadPage/edLadingPage/addModules.html?v=" + v,
        controller: ["$scope", function ($scope) {
          // alert(333)
          $scope.closeModules = function(){
            $scope.showAddmodules = false;
          }


          $scope.stateGo = function(v){
            if(v==1){                               // 打开轮播图模块
              $scope.showSwiperEditLayer = true;
              $scope.showAddmodules = false;
              $scope.swiperData={
                moduleType:'1',       // 模块类型 1 轮播图
                switchTime:'3',       //默认3秒
                switchView:'1',       // 1是从右往左  2是淡入淡出
                upPadding:'0',
                downPadding:'0',
                width:'2',
                hight:'1',
                bannerList:[],
                editorId:''
              }
            }else if(v==2){                         // 打开编辑器模块
              $scope.showEditorLayer = true;
              $scope.showAddmodules = false;
              $scope.editor={
                pageLoadContent:'',
                moduleType:'2',
                id:0,
                editorId: ''
              }
            }else{
              // 打开信息收集器模块
              var judge = $scope.allList.some(function(item){     // 利用数组的some方法返回true /false 判断allList里是否有信息收集器
                return item.moduleType === '3'
              })
              console.log(judge)
              if(judge){
                $scope.alertModel({
                  text: '“只能添加一个收集器！',
                  resCode: '00001',
                })
              }else{
                $scope.showInforLayer = true;
                $scope.showAddmodules = false;
              }

            }
          }
        }]
      }
    })
    /*轮播弹框 */
    .directive('swiperEdit', function () {
      return {
        restrict: 'E',
        scope: {
          showSwiperEditLayer: '=isShowSwiperEditLayer',
          isShowList1: '&',
          swiperData:'='
        },
        templateUrl: "./src/app/toolChest/loadPage/edLadingPage/swiperEdit.html?v=" + v,

        controller: ["$scope", 'ajaxRquest','$rootScope', function ($scope, ajaxRquest, $rootScope) {
          $scope.showWarning=false    //控制警告是否显现
          $scope.effects=[    //切换效果下拉框
            {'id':'1','value':'从右往左'},
            {'id':'2','value':'淡入淡出'}
          ]
          $scope.sizes=[     //比例尺寸下拉框
            {'id':'1','value':'2:1'},
            {'id':'2','value':'1:1'}
          ]
          $scope.checkInput=function(){
            // console.log("111")
            if(!(/^[0-9]*$/.test(event.target.value))){
              event.target.value=''
            }
          }
          $scope.turnToThree=function(){
            if($scope.swiperData.switchTime<3 || $scope.swiperData.switchTime<'3'){
              $scope.swiperData.switchTime='3'
            }
          }
          if ($scope.swiperData) { // 判断是否有图片，有就回显
            $scope.swiperDataCopy = JSON.parse(JSON.stringify($scope.swiperData)) // 备份
          }
          $scope.imgData = []
          $scope.swiperData.width + ':' + $scope.swiperData.hight === '2:1' ? $scope.widthHeight = '1' : $scope.widthHeight = '2' // 根据传进来的值来确定比例

          // 打开或关闭swiper模块弹框
          $scope.ifShowSwiperEditLayer = function () {
            $scope.imgData = []
            $scope.showSwiperEditLayer = false
            for(var i in $scope.swiperDataCopy){
              $scope.swiperData[i]=$scope.swiperDataCopy[i]
            }
            // $scope.isShowList1()
          }

          // 上传图片监听（添加按钮的）
          $scope.uploadSuccess = function () {
            $scope.swiperData.bannerList.push({
              bannerImg: $scope.imgData[0].src[0],
              bannerLink: ''
            })
            $scope.sort()
            $scope.imgData = []
          }
          $scope.sort = function () {
            $scope.swiperData.bannerList.forEach(function(item,index){
              item.sort=index
            })
          }
          // 上传图片监听（重新上传的）
          $scope.thisUploadSuccess = function (v) {
            $scope.swiperData.bannerList[v].src = $scope.thisImgSrc[0].src[0]
            $scope.swiperData.bannerList[v].bannerImg = $scope.thisImgSrc[0].src[0]
            $scope.thisImgSrc = []
          }

          // 删除事件
          $scope.deleteEvent = function (index) {
            $rootScope.alertModel({
              text: '您将删除此张图片！', // 内容
              btnCancel: true, // 取消按钮
              btnConfirm: true, // 确认按钮
              resCode: '00001',
              closeSelf: false
            }).then(function () {
              $scope.$apply(function(){
                $scope.swiperData.bannerList.splice(index, 1),
                    $scope.sort()
              })
            })
          }



          // if($scope.swiperData.bannerList.length){     //判断是否有图片，有就回显
          //   // console.log('y')
          //   $scope.swiperDataCopy=angular.copy($scope.swiperData)
          //   $scope.imgData=angular.copy($scope.swiperData.bannerList)
          //   angular.forEach($scope.imgData,function(item,index){
          //     item.src=item.bannerImg
          //   })
          // }else{
          //   $scope.imgData=[]
          // }
          // // console.log($scope.imgData)
          // $scope.swiperData.width+':'+$scope.swiperData.hight ==='2:1' ? $scope.widthHeight='1' : $scope.widthHeight='2'    //根据传进来的值来确定比例
          // // $scope.widthHeight='1'
          // $scope.ifShowSwiperEditLayer = function () { // 打开或关闭swiper模块弹框
          //   $scope.showSwiperEditLayer = false
          //   $scope.swiperData= $scope.swiperDataCopy
          // }
          //
          // $scope.uploadSuccess=function(){    //上传图片监听（添加按钮的）
          //   console.log($scope.imgData)
          //   if($scope.swiperDataCopy){    //每次添加图片先初始 $scope.swiperData.bannerList，从编辑入口，则还原成回显的数据，新增入口则还原清空
          //     $scope.swiperData.bannerList=angular.copy($scope.swiperDataCopy.bannerList)
          //   }else{
          //     $scope.swiperData.bannerList=[]
          //   }
          //   angular.forEach($scope.imgData,function(item){    //将$scope.imgData合并到$scope.swiperData.bannerList中
          //     $scope.swiperData.bannerList.push(item)
          //   })
          //   angular.forEach($scope.swiperData.bannerList,function(item,index){
          //     if(item.src){
          //       // 取出数组的值 item.bannerImg=item.src[0] ??
          //       item.bannerImg=item.src[0]
          //       console.log(item.src)
          //     }
          //     if(!item.bannerLink){
          //       item.bannerLink=''
          //     }
          //   })
          // }
          // $scope.thisUploadSuccess=function(v){    //上传图片监听（重新上传的）
          //   $scope.swiperData.bannerList[v].src=$scope.thisImgSrc[0].src[0]
          //   $scope.swiperData.bannerList[v].bannerImg=$scope.thisImgSrc[0].src[0]
          //   $scope.thisImgSrc=[]
          // }
          // $scope.deleteEvent=function(index){    //删除事件
          //
          //     $scope.swiperData.bannerList.remove($scope.swiperData.bannerList[index])
          //   console.log("11111");
          //   console.log($scope.swiperData.bannerList);
          //
          // }
          $scope.downEvent=function(index){    //下移事件
            if(index!==$scope.swiperData.bannerList.length-1){    //如果是最后一个，无法下移
              var emptyContain=[]
              emptyContain=$scope.swiperData.bannerList[index]
              $scope.swiperData.bannerList[index]=$scope.swiperData.bannerList[index+1]
              $scope.swiperData.bannerList[index+1]=emptyContain
            }

          }
          $scope.upEvent=function(index){    //上移事件
            if(index!==0){         //如果是第一个，无法上移
              var emptyContain=[]
              emptyContain=$scope.swiperData.bannerList[index]
              $scope.swiperData.bannerList[index]=$scope.swiperData.bannerList[index-1]
              $scope.swiperData.bannerList[index-1]=emptyContain
            }

          }

          $scope.sureEvent=function(){      //确认事件，将本次的数据放入落地页的总数据中等候提交
            if($scope.widthHeight==='1'){
              $scope.swiperData.width='2'
              $scope.swiperData.hight='1'
            }else if($scope.widthHeight==='2'){
              $scope.swiperData.width='1'
              $scope.swiperData.hight='1'
            }
            if($scope.swiperData.bannerList.length>0){
              $scope.isShowList1()
              $scope.showSwiperEditLayer = false
            }else{
              $scope.showWarning=true
            }
          }
        }]
      }
    })
    /*编辑器弹框 */
    .directive('editorEdit', function () {
      return {
        restrict: 'E',
        scope: {
          showEditorLayer: '=isShowEditorLayer',
          isShowList2: '&',
          editor:'='
        },
        templateUrl: "./src/app/toolChest/loadPage/edLadingPage/editorEdit.html?v=" + v,
        controller: ["$scope", 'ajaxRquest','$rootScope', '$timeout',function ($scope, ajaxRquest,$rootScope,$timeout) {
          var ue = UE.getEditor('edit',{      //初始化富文本
            toolbars: [
              ['simpleupload', 'undo', 'redo', 'bold', 'italic',
                'underline','fontborder', 'backcolor', 'fontsize', 'fontfamily',
                'justifyleft', 'justifyright','justifycenter', 'justifyjustify',
                'strikethrough','forecolor']
            ],
            serverUrl:"/iFengChao-SYS-Web/upload/uploadUMImage",
            initialFrameWidth : 600,    //设置默认宽
            initialFrameHeight: 316    //设置默认高
          });
          // setTimeout(function () {
          //   ue.execCommand('drafts');
          // }, 500); //注意一定要延时。要等这玩意载入成功。
          console.log($scope.editor)
          if($scope.editor.pageLoadContent){
            $scope.editorCopy=angular.copy($scope.editor)
          }
          ue.ready(function() {
            UE.getEditor('edit').setContent($scope.editor.pageLoadContent);
          })
          $scope.ifShowEditorLayer = function () { // 打开或关闭swiper模块弹框
            $scope.showEditorLayer = false
            $scope.editor=$scope.editorCopy
            ue.destroy()
          }

          $scope.sureEvent = function (){
            var html = UE.getEditor('edit').getContent();   //获取编辑器html内容
            $scope.editor.pageLoadContent=html
            $scope.showEditorLayer = false
            if($scope.editor.pageLoadContent){
              $scope.isShowList2()
              console.log($scope.editor)
            }else{
              $scope.editor=$scope.editorCopy
            }
            // setTimeout(function() {
            //   ue.destroy()
            // }, 3000);
            ue.destroy()
          }
        }]
      }
    })
    /*信息收集器弹框 */
    .directive('informationModules', function () {
      return {
        restrict: 'E',
        scope: {
          copyInfor: '=isCopyInfor',
          showInforLayer: '=isShowInforLayer',
          isShowList3: '&',
          // isEmpty2: '&'
        },
        templateUrl: "./src/app/toolChest/loadPage/edLadingPage/informationModules.html?v=" + v,
        controller: ["$scope", 'ajaxRquest','$rootScope', function ($scope, ajaxRquest, $rootScope) {
          // $scope.showInforLayer = false;
          $scope.inforAmount = [             // 字段信息 数据
            {
              collectList: [{
                fieldName: '',
                textType: [
                  {
                    value: '文本框',
                    id: '0'
                  },
                  {
                    value: '下拉框',
                    id: '1'
                  },
                  {
                    value: '复选框',
                    id: '2'
                  }
                ],
                requiredType: [
                  {
                    value: '必填',
                    id: 'Y'
                  },
                  {
                    value: '非必填',
                    id: 'N'
                  }
                ],
                id: 0,
                selectType: '0',
                selectDetai: '',
                needCheck	:''
              }],
              pageloadIndex: '',
              moduleType: '3'
            }
          ];
          $scope.addInforWrap = function(){           // 添加inforwrap  方法
            $scope.inforAmount[0].collectList.push(
                {
                  fieldName: '',
                  textType: [
                    {
                      value: '文本框',
                      id: '0'
                    },
                    {
                      value: '下拉框',
                      id: '1'
                    },
                    {
                      value: '复选框',
                      id: '2'
                    }
                  ],
                  requiredType: [
                    {
                      value: '必填',
                      id: 'Y'
                    },
                    {
                      value: '非必填',
                      id: 'N'
                    }
                  ],
                  id: 0,
                  selectType: '0',
                  selectDetai: '',
                  needCheck	:''
                });
          }
          $scope.deleteInfor = function(index){
            $scope.inforAmount[0].collectList.splice(index,1)
          }
          $scope.string2Array = function (stringObj) {                  // 将字符串转换为数组
            // stringObj = stringObj.replace(/([\w,]∗)/, "$1");
            // if (stringObj.indexOf("[") == 0) {// if has chinese
            //   stringObj = stringObj.substring(1, stringObj.length - 1);
            // }
            // var arr = [];
            // if(stringObj.indexOf('，')!=-1){  // 中文逗号
            //   arr = stringObj.split("，");
            // }else if(stringObj.indexOf(',')!=-1){   // 英文逗号
            //   arr = stringObj.split(",");
            // }else if(stringObj.indexOf('、')!=-1){   // 顿号
            //   arr = stringObj.split("、");
            // }else if(stringObj.indexOf(' ')!=-1){    // 空格
            //   arr = stringObj.split(" ");
            // }else{
            //   arr= stringObj
            // }
            // var newArray = [];//new Array();
            // console.log(arr)
            // for ( var i = 0; i < arr.length; i++) {
            //   var arrOne = arr[i];
            //   newArray.push(arrOne);
            // }
            // // console.log(newArray);
            // return newArray;
            var arr = []
            if(stringObj.indexOf('，') != -1) { // 中文逗号
              arr = stringObj.split('，')
            }else if (stringObj.indexOf(',') != -1) { // 英文逗号
              arr = stringObj.split(',')
            }else if (stringObj.indexOf('、') != -1) { // 顿号
              arr = stringObj.split('、')
            }else if (stringObj.indexOf(';') != -1) { // 分号
              arr = stringObj.split(';')
            }else if (stringObj.indexOf('；') != -1) { // 分号
              arr = stringObj.split('；')
            }else if (stringObj.indexOf('/') != -1) { // 斜杠
              arr = stringObj.split('/')
            }else if (stringObj.indexOf('／') != -1) { // 斜杠
              arr = stringObj.split('／')
            }else {
              arr = stringObj
            }
            var newArray = []; // new Array()
            if(arr instanceof Array){
              for ( var i = 0; i < arr.length; i++) {
                var arrOne = arr[i]
                newArray.push(arrOne)
              }
            }else{
              newArray.push(arr)
            }
            return newArray
          };
          $scope.addInformation = function(){            // 确定按钮
            $scope.inforAmount[0].collectList.forEach(function(item){    // 将selectDetai转换为数组
              console.log(item.selectDetai)
              if(item.selectDetai){
                item.selectDetai = $scope.string2Array(item.selectDetai)
              }
            })
            $scope.copyInfor = $scope.inforAmount[0]
            for(var i=0;i<$scope.inforAmount[0].collectList.length;i++){
              if($scope.inforAmount[0].collectList[i].fieldName===''){
                $rootScope.alertModel({
                  text: '字段名称不能为空',
                  resCode: '00001'
                })
                return false
              }else if($scope.inforAmount[0].collectList[i].selectType!=='0' && $scope.inforAmount[0].collectList[i].selectDetai===''){
                $rootScope.alertModel({
                  text: '选项值不能为空',
                  resCode: '00001'
                })
                return false
              }
            }
            $scope.showInforLayer = false;
            console.log($scope.copyInfor)
            $scope.isShowList3({a:$scope.copyInfor})
          }
          $scope.closeInfor = function(v){
            $scope.showInforLayer = false;
            $scope.copyInfor = {}
          }
        }]
      }
    })
    .controller('edLadingPageController',['$scope','$filter','$timeout','$state','$stateParams','$sce','$rootScope',function( $scope,$filter,$timeout,$state,$stateParams,$sce,$rootScope) {
        if ($state.includes('**.loadPage.update')) {
            $scope.title = "编辑模板";
            var pageLoadId = $state.params.pageLoadId;
            $scope.editor1 = 1;
            activate(pageLoadId);
        } else if ($state.includes('**.loadPage.save')) {
            $scope.title = "新增模板";
            $scope.record = {};
            setTimeout(function () {
                !$rootScope.$$phase && $scope.$apply();
            }, 300);
        }
        // 初始化页面
        function activate(pageLoadId) {
            $scope.loading = true;
            $.ajax({
                url: $scope.app.project_name + '/loadPage/detail',
                data: {'loadPageId': pageLoadId}
            }).then(function (result) {
                $scope.loading = false;
                $scope.record = result.data;
                console.log($scope.record)
                if (result.httpCode == 200) {
                    $scope.$apply(function(){
                        $scope.record.detailList.forEach(function(item){
                            console.log(item.collectList)
                            if(item.moduleType==3){
                                item.collectList.forEach(function(v){
                                    console.log(v.selectDetai)
                                    if(v.selectDetai){
                                        v.selectDetai = $scope.string2Array(v.selectDetai)
                                    }
                                })
                            }
                        })
                        $scope.allList = $scope.record.detailList;
                        $scope.imgData = [];
                        var srcArr = [];
                        srcArr.push($scope.record.moduleImg);
                        $scope.logoImg.push({
                            src: srcArr
                        })
                        $scope.tag = String($scope.record.loadPageType)
                        $scope.pageDetail = $scope.record
                    })
                } else {
                    $scope.msg = result.msg;
                }
                $scope.$apply();
            });
        }
      var _this=this;
      $scope.showAddmodules=false
      $scope.accoundId = $.cookie('accountId')            // 获得cookie里面保存的accountId
      $scope.changeEditor = false;
      // $scope.editor = $stateParams.val;
      if ($scope.editor && $scope.editor == 1) {         // 通过判断$stateParams.val的值 显示是否是编辑页面还是新增页面
        $scope.changeEditor = !$scope.changeEditor
      }

      $scope.PPuploadSuccess=function(){
        // console.log("111");
        console.log($scope.logoImg)
      }
      $scope.search = function () {
        // $scope.loading = true;
        // $scope.searchParams.pageNum = 1;
        // $scope.selected = [];
        $.ajax({
          url : $scope.app.project_name+ '/loadPage/getFromWork'
          // data: $scope.searchParams
        }).then(function(result) {
          // $scope.loading = false;
          if (result.httpCode == 200) {
            $scope.flowType = result.data;
            $scope.tag = String(result.data[0].loadPageType)
            // console.log($scope.tag)
            console.log($scope.flowType);
          } else {
            $scope.msg = result.msg;
          }
          $scope.$apply();
        });
      };
      $scope.search();
      // $scope.flowType = [
      //   {
      //     value: '流量类型',
      //     id: ''
      //   },
      //   {
      //     value: 'Web',
      //     id: '1'
      //   },
      //   {
      //     value: 'App',
      //     id: '2'
      //   }
      // ];
      $scope.tabIndex = undefined;   // 默认 全部
      // 数据
      $scope.tabNum = [             // tab 数据
        {
          name: '全部',
          id: ''
        },
        {
          name: '体育',
          id: ''
        },
        {
          name: '电商',
          id: ''
        },
      ]
      $scope.selectAll = false
      // 分页
      $scope.allPagingData = {
        'total': 10,
        'currentPage': 1,
        'paginLength': 6,
        'pageSize': '10'
      };
      $scope.swtchTab = function(v,item){     // tab 点击哪个，哪个加上class:tabModule
        $scope.tabIndex = v;
        console.log(v)
        if(item){
          $scope.getModulesList(item.loadPageType)
        }else{
          $scope.getModulesList()
        }
      }

      /*******************************  落地页模版 移动********************************************************** */
      // $scope.leftNum = {                // 设置的移动的初始值
      //   transform:'translateX(0px)',
      //   width:''
      // }
      // $scope.addNum = 0;
      // $scope.toRight = function(){      // 点击右移
      //   $scope.move(-1)
      //   // $scope.allPagingData.currentPage++
      //   // $scope.getModulesList()
      // }
      // $scope.toLeft = function(){       // 点击左移
      //   $scope.move(1)
      // }
      // var i=0;
      // var swiperUl = document.getElementById('swiperUl')
      // var cutter=document.getElementById('cutter')
      //
      // _this.translatex=0
      // var dis=0;

      // $scope.move=function(direction){   // 轮播图的移动方法
      //   _this.dat=parseInt(getStyle(swiperUl,'width'))-parseInt(getStyle(cutter,'width'))
      //   if(_this.onoff){
      //     return
      //   }
      //   if(direction<0&&$scope.datWidth==20){
      //     return false
      //   }
      //   var offset=140;
      //   if(direction<0&&dis>20-_this.dat){
      //     i--
      //   } else if(direction>0){
      //     i++
      //   }
      //   if(i>0){
      //     i=0
      //   }
      //   dis=offset*i
      //
      //   if(direction<0&&$scope.datWidth<140){
      //     dis=20-_this.dat
      //     _this.onoff=false
      //   }
      //   if(_this.translatex==0&&direction>0){
      //     _this.onoff=false
      //     return
      //   }
      //   $scope.leftNum.transition='all 0.5s'
      //   $scope.leftNum['webkit-transition']='all 0.5s'
      //   $scope.leftNum.transform='translateX('+dis+'px)'
      //   $scope.leftNum['webkit-transform']='translateX('+dis+'px)'
      //   _this.onoff=true
      // }
      // function calculateX(){
      //   _this.translatex=getStyle(swiperUl,'transform').split('(')[1].split(')')[0].split(',')[4];
      //   $scope.datWidth=_this.dat+ +_this.translatex
      //   _this.onoff=false
      // }
      // swiperUl.addEventListener('transitionend',calculateX)
      /**********  模板 *********** */
      $scope.getModulesList = function(type){
        $.ajax({
          url: url,
          type: 'POST',
          data: {
            userSlaveId: $.cookie('accountId'),                 // String 用户从表id（默认99999999）是
            pageSize: $scope.allPagingData.pageSize,                       // nt 每页条数 否
            current: $scope.allPagingData.currentPage,                     // int 当前页码 否
            loadPageType: type                                          // int 模板类别	 否
          }
        }).then(function (res) {
          console.log(res)
        })
        // 模板接口
        // ajaxRquest.getData('/toolManageCrtExt/getLoadPageFromWork',
        //     {
        //       userSlaveId: $.cookie('accountId'),                 // String 用户从表id（默认99999999）是
        //       pageSize: $scope.allPagingData.pageSize,                       // nt 每页条数 否
        //       current: $scope.allPagingData.currentPage,                     // int 当前页码 否
        //       loadPageType: type                                          // int 模板类别	 否
        //     }).then(function(res){
        //   console.log(res);
        //   if(res.resCode==='00000'){
        //     $scope.$apply(function(){
        //       $scope.picModules = res.records;
        //       $scope.tabNum = res.records1;
        //       $scope.allPagingData.total = res.total
        //       $scope.leftNum.width=$scope.picModules.length*140+'px'
        //       setTimeout(function(){
        //         $scope.datWidth=parseInt(getStyle(swiperUl,'width'))-parseInt(getStyle(cutter,'width'))
        //       },10)
        //     })
        //   }else{
        //     $scope.alertModel({
        //       text: res.resMsg,
        //       resCode: res.resCode
        //     })
        //   }
        // })
      }
      // $scope.getModulesList()


      /******************************展示 h5页面**************************************************** */
      $scope.deleteForm = function(item){     // 删除模块方法
        $scope.alertMessage({
          text:"确定做此操作吗？", //内容
          btnCancel:true, //取消按钮
          btnConfirm:true //确认按钮
        }).then(function () {
          $scope.$apply(function(){
            $scope.allList.splice(item,1);
          })

        })

      }
      $scope.allList = [];

      $scope.copyForm = function(v,i){   // 信息收集器复制按钮
        console.log(v)
        console.log(i)
        $scope.copyV = JSON.parse(JSON.stringify(v))
        $scope.alertModel({
          text: '是否确定复制？',
          resCode: '00001',
          btnCancel: true
        }).then(function(){
          $scope.$apply(function(){
            $scope.copyV.collectList.forEach(function(item){
              item.isCopy = true
            })
            // $scope.copyV.collectList[0].isCopy = true
            $scope.allList.push($scope.copyV)
            console.log($scope.allList)
            // $scope.isCopy = true
          })
        },function(){
          return
        })
      }


      // 信息收集器 确定
      $scope.isShowList3 = function (v) {
        console.log($scope.allList)
        var judge = $scope.allList.some(function(item){     // 利用数组的some方法返回true /false 判断allList里是否有信息收集器
          return item.moduleType === '3'
        })
        console.log(judge)
        if(judge){
          $scope.alertModel({
            text: '“只能添加一个收集器！',
            resCode: '00001',
          })
        }else{
          $scope.allList.push(v)
        }
      }
      // 编辑器 确定
      $scope.isShowList2 = function () {
        console.log($scope.editor)
        if($scope.editor.editorId&&$scope.editor.editorId===$scope.allList[$scope.editor.editorId].editorId){
          for(var i=0;i<$scope.allList.length;i++){
            if($scope.allList[i].editorId===$scope.editor.editorId){
              $scope.allList[i] = $scope.editor
            }
          }
        }else{
          $scope.allList.push($scope.editor)
        }
        console.log($scope.allList)
      }
      // 轮播图 确定
      $scope.isShowList1 = function () {
        console.log($scope.swiperData)
        if($scope.swiperData.editorId&&$scope.swiperData.editorId===$scope.allList[$scope.swiperData.editorId].editorId){
          // alert(1)
          // $scope.allList.splice(0,$scope.allList[$scope.swiperData.editorId],$scope.swiperData)
          for(var i=0;i<$scope.allList.length;i++){
            if($scope.allList[i].editorId===$scope.swiperData.editorId){
              $scope.allList[i] = $scope.swiperData
            }
          }
        }else{
          $scope.allList.push($scope.swiperData)
        }
        console.log($scope.allList)
      }
      /****************************** 编辑 *******************************************/
      $scope.string2Array = function (stringObj) {              // 字符串转成数组
        stringObj = stringObj.replace(/([\w,]∗)/, "$1");
        if (stringObj.indexOf("[") == 0) {// if has chinese
          stringObj = stringObj.substring(1, stringObj.length - 1);
        }
        var arr = [];
        if(stringObj.indexOf('，')!=-1){  // 中文逗号
          arr = stringObj.split("，");
        }else if(stringObj.indexOf(',')!=-1){   // 英文逗号
          arr = stringObj.split(",");
        }else if(stringObj.indexOf('、')!=-1){   // 顿号
          arr = stringObj.split("、");
        }else if(stringObj.indexOf(' ')!=-1){    // 空格
          arr = stringObj.split(" ");
        }else{
          arr = stringObj
        }
        var newArray = [];//new Array();
        for ( var i = 0; i < arr.length; i++) {
          var arrOne = arr[i];
          newArray.push(arrOne);
        }
        // console.log(newArray);
        return newArray;
      };
      $scope.inforNum = 0;
      $scope.moduleNum = null;
      /***** 编辑 落地页接口********/
      $scope.ladingPageId = $stateParams.ladingPageId
      $scope.editorDetails = function(){                        // 编辑 下 ， 落地页详情接口
        ajaxRquest.getData('/toolManageCrtExt/queryLoadPageDetail',{
          loadPageId: $scope.ladingPageId                      // 落地页id
        }).then(function(res){
          console.log(res)
          if(res.resCode==='00000'){
            $scope.$apply(function(){
              res.record.detailList.forEach(function(item){
                console.log(item.collectList)
                if(item.moduleType==3){
                  $scope.inforNum++;
                  item.collectList.forEach(function(v){
                    console.log(v.selectDetai)
                    if(v.selectDetai){
                      v.selectDetai = $scope.string2Array(v.selectDetai)
                    }
                  })
                }
              })
              var processArr = res.record.detailList.filter(function(value){
                return value.moduleType == 3
              })
              $scope.moduleNum = processArr.length
              $scope.allList = res.record.detailList
              $scope.pageDetail = res.record
            })
          }else{
            $scope.alertModel({
              text: res.resMsg,
              resCode: res.resCode
            })
          }
        })
      }

      $scope.editorText = function(item,index,val){              // 编辑富文本
        item.editorId = index+'';
        $scope.showEditorLayer = true;
        $scope.editor=item
      }
      if($scope.editorLoadingPage==1){
        $scope.editorDetails()
      }
      $scope.editorPic = function(item,index){                  //  编辑轮播图
        console.log(item)
        item.editorId = index+'';
        $scope.showSwiperEditLayer = true;
        $scope.showAddmodules = false;
        $scope.swiperData=item
      }
      function getStyle(obj, property) {
        return document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(obj, false)[property] : obj.currentStyle[property]
      }

      $scope.modifyList = function(){     //  处理最终要新增保存的数据
        console.log($scope.allList)
        $scope.setSwiperData = [];
        $scope.setinforData = [];
        $scope.setTextData = [];
        if($scope.editor1 && $scope.editor1 == 1){      // 编辑下的最终数据
          $scope.allList.forEach(function(item,index){
            if(item.moduleType==1){           // 轮播图
              if(item.bannerFormatId&&item.bannerFormatId!=''){
                item.dealType = 'modify';
                item.bannerFormatId = item.bannerFormatId;
              }else{
                item.dealType = 'add';
                item.bannerFormatId = '';
              }
              item.pageLoadIndex = index+''
              console.log(item.pageLoadIndex)
              $scope.setSwiperData.push(item)
              console.log($scope.setSwiperData)
            }
            if(item.moduleType==2){           // 编辑器
                if (item.contentId) {
                    item.dealType = 'modify'
                    item.contentId = item.contentId
                }else {
                    item.dealType = 'add'
                    item.contentId = ''
                }
                item.pageLoadIndex = index + ''
                $scope.setTextData.push(item)
              console.log($scope.setTextData)
            }
            if(item.moduleType==3){           // 信息收集器
              item.collectList.forEach(function (v,i) {
                // if(v.collectId && v.collectId !== ''&&$scope.chooseData && $scope.chooseData== 2){  // 从模版处添加进来的，然后新增
                //   v.dealType = 'add'
                //   v.collectId = ''
                //   v.pageLoadIndex = index + ''
                //   v.collectIndex = index
                // }else
                if (v.collectId && v.collectId !== ''&& v.isCopy==undefined )  {      // 判断collectId是否存在，存在即是编辑
                  v.dealType = 'modify'
                  v.collectId = v.collectId
                  v.pageLoadIndex = index + ''
                  v.collectIndex = index + ''
                }else if(v.collectId && v.collectId !== ''&&v.isCopy){              // 判断iscopy存在即是复制出来的
                  v.dealType = 'add'
                  v.collectId = ''
                  v.pageLoadIndex = index + ''
                  v.collectIndex = index + ''
                }else{
                  v.dealType = 'add'
                  v.collectId = ''
                  v.pageLoadIndex = index + ''
                  v.collectIndex = index
                }
                v.moduleType = '3'
                v.textType = undefined
                v.requiredType = undefined
                v.id = undefined
                delete v.textType
                delete v.requiredType
                delete v.id
              })
              $scope.setinforData.push(item.collectList)
            }
          })
        }else{
          $scope.allList.forEach(function(item,index){    //  新增下的最终数据
            if(item.moduleType==1){           // 轮播图
              item.dealType = 'add';
              item.pageLoadIndex = index + '';
              item.bannerFormatId = item.bannerFormatId?item.bannerFormatId+'':''
              $scope.setSwiperData.push(item)
              console.log($scope.setSwiperData)
            }
            if(item.moduleType==2){           // 编辑器
              item.dealType = 'add';
              item.pageLoadIndex = index + ''
              item.contentId = item.contentId?item.contentId+'':''
              $scope.setTextData.push(item)
              console.log($scope.setTextData)
            }
            if(item.moduleType==3){           // 信息收集器
              console.log($scope.setinforData)
              item.collectList.forEach(function(v){
                v.dealType = 'add';
                v.pageLoadIndex = index + '';
                v.moduleType = '3';
                v.textType = undefined;
                v.requiredType = undefined;
                v.collectId = v.collectId?v.collectId+'':'';
                v.collectIndex = index + '';
                delete v.textType;
                delete v.requiredType
              })
              $scope.setinforData.push(item.collectList)
            }
          })
          console.log($scope.setinforData)
        }
        console.log($scope.setinforData)
        if($scope.setinforData.length!=0){
          $scope.setinforData.forEach(function(item){    // 将之前转换数组的字符串重新转换为字符串
            item.forEach(function(v){
              if(v.selectDetai instanceof Array){
                v.selectDetai = v.selectDetai.join(',');
              }
            })
          })
        }
      }
      /*****  新增 保存 接口**********/
      $scope.pageDetail = {
        loadPageName: ''
      }
      $scope.addSave = function(){
        if($scope.editor1 && $scope.editor1 == 1){
          $scope.saveType = 'modify'
        }else{
          $scope.saveType = 'add'
        }

        // if($scope.logoImg[0]=='' || $scope.logoImg[0]==undefined || $scope.logoImg[0]=="undefined"){
        //   $scope.alertModel({
        //     text: '封面不能为空',
        //     resCode: '00001'
        //   })
        //   return
        // }
        
        if($scope.pageDetail.loadPageName=='' || $scope.pageDetail.loadPageName==undefined){
          $scope.alertModel({
            text: '落地页名称不能为空',
            resCode: '00001'
          })
          return
        }
        $scope.modifyList();
        console.log($scope.setSwiperData);
        console.log($scope.setTextData);
        console.log($scope.setinforData)
        // $scope.setTextData = [{name:"123",ege:"12"},{name:"123",ege:"12"}]
        // for(var i=0;i<$scope.setTextData.length;i++){
        //     alert($scope.setTextData[i]);
        // }
        // var loadpageId=$scope.pageDetail.loadPageId?$scope.pageDetail.loadPageId+'':'';
        // var from;
        // from="{loadpageName:"+$scope.pageDetail.loadPageName+",loadpageId:"+$scope.pageDetail.loadPageId+",loadpageDealType:"+$scope.saveType+",contentTotalMesg:"+JSON.stringify($scope.setTextData)+"}"
        // console.log("222222")

        // console.log($scope.logoImg[0].src);

        $.ajax({
          url: $scope.app.project_name+'/loadPage/save',
          type: 'POST',
          data: {
            'loadpageName': $scope.pageDetail.loadPageName, // 落地页名称
            'keyword':$scope.pageDetail.keyword,
            'description':$scope.pageDetail.description,
            'loadpageType':$scope.tag,
            'moduleImg':$scope.logoImg[0] ? $scope.logoImg[0].src[0] : '',
            'scriptContent':$scope.pageDetail.scriptContent,
            'userIdS': $scope.accoundId+"",
            'loadpageId': $scope.pageDetail.loadPageId?$scope.pageDetail.loadPageId+'':'',
            'loadpageDealType': $scope.saveType,          // 新增or 修改
            'bannerTotalMesg': JSON.stringify($scope.setSwiperData),
            'contentTotalMesg': JSON.stringify($scope.setTextData),
            'collectTotalMesg': JSON.stringify($scope.setinforData)
          }
        }).then(function (res) {
          // console.log("aaaa");
          // console.log(res)
          // if(res.httpCode=200){
            //成功跳转页面
            $state.go('main.toolChest.loadPage.model');
          // }
        })
        // ajaxRquest.getData('/toolManageCrtExt/editLoadpageInfo',{
        //   loadpageName: $scope.pageDetail.loadPageName, // 落地页名称
        //   userIdS: $scope.accoundId+"",
        //   loadpageId: $scope.pageDetail.loadPageId?$scope.pageDetail.loadPageId+'':'',
        //   loadpageDealType: $scope.saveType,          // 新增or 修改
        //   bannerTotalMesg: $scope.setSwiperData?$scope.setSwiperData:[],
        //   contentTotalMesg: $scope.setTextData?$scope.setTextData:[],
        //   collectTotalMesg: $scope.setinforData?$scope.setinforData:[]
        // }).then(function(res){
        //   console.log(res)
        //   if(res.resCode==='00000'){
        //     $rootScope.saveAlert('保存成功').then(function(){
        //       $state.go('main.ladingPage')
        //     })
        //   }else{
        //     $scope.alertModel({
        //       text: res.resMsg,
        //       resCode: res.resCode
        //     })
        //   }
        // })
      }
    }])
angular.module('app').filter('to_trusted', ['$sce', function ($sce) {
  return function (text) {
    return $sce.trustAsHtml(text);
  };
}]);